<template>
  <el-dialog
    class="troila-dialog"
    :title="`${title}组织机构`"
    :visible.sync="dialogFormVisible"
    :modal-append-to-body="true"
    :append-to-body="true"
    width="600px"
  >
    <el-form
      class="troila-form"
      :label-width="formLabelWidth"
      :model="form"
      :rules="rules"
      ref="form"
    >
      <el-form-item label="所属机构" prop="pid">
        <treebox
          id="treebox"
          :list="menus"
          v-model="form.pid"
          placeholder="请选择"
          input
          onlyone
          :option="{ key: 'id', label: 'organizationName' }"
          :loading="loading"
          :disabled="disabled"
          :clear="!disabled"
          @return="returnTree"
        ></treebox>
      </el-form-item>
      <el-form-item label="机构名称" prop="organizationName">
        <el-input
          v-model="form.organizationName"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="机构类型" prop="organizationType">
        <el-select
          v-setwidth
          placeholder="请选择"
          v-model="form.organizationType"
          clearable
          popper-class="troila-popper"
          @click.native="$store.commit('treeboxFn', null)"
        >
          <el-option
            v-for="(item, index) in organizationType"
            :key="index"
            :label="item.dictName"
            :value="item.dictCode"
            :disabled="judgeDisabled(item)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="principal">
        <el-input
          v-model="form.principal"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="form.phone"
          auto-complete="off"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <input-num v-model="form.sort" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="ajaxIng" @click="submitForm"
        >确 定</el-button
      >
      <el-button @click="dialogFormVisible = false">{{
        ajaxIng ? '关 闭' : '取 消'
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { checkPhone } from '../../../../../assets/js/validate'
export default {
  name: 'menuForm',
  props: {
    value: {
      // true为添加，其他为编辑
      type: [Boolean, String, Number, Object],
      default: false,
    },
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value && !checkPhone(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      ajaxIng: false,
      dialogFormVisible: this.value ? true : false, //弹窗显示
      title: '',
      form: {
        pid: '',
        organizationName: '',
        organizationType: '',
        principal: '',
        phone: '',
        sort: '',
      },
      formLabelWidth: '120px', //标题文字宽度
      rules: {
        // 规则
        pid: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
        organizationName: [
          { required: true, message: '请输入机构名称', trigger: 'blur' },
        ],
        organizationType: [
          { required: true, message: '请选择机构类型', trigger: 'change' },
        ],
        phone: [{ validator: validateMobile, trigger: 'blur' }],
      },
      dictionary: {
        // 字典信息
        // organizationType: [
        //   { dictName: '目录', dictCode: 0 },
        //   { dictName: '菜单', dictCode: 1 },
        //   { dictName: '按钮', dictCode: 2 },
        // ],
        // menuStatus: [
        //   { dictName: '禁用', dictCode: '0' },
        //   { dictName: '启用', dictCode: '1' },
        // ],
      },
      menus: [],
      disabled: false,
    }
  },
  computed: {
    organizationType() {
      let list = this.$store.state.dictionary.organization_type
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'organization_type')
      }
      this.dictionary.dictType = list
      return list ? list : []
    },
  },
  watch: {
    value(v) {
      let show = v ? true : false,
        change = false
      this.dialogFormVisible !== show
        ? ((this.dialogFormVisible = show), (change = true))
        : null
      if (v && change) {
        this.getTree()
        this.title = v.method === 'add' ? '添加' : '修改'
        this.$refs.form ? this.$refs.form.resetFields() : null
        if (typeof v === 'object') {
          for (let k in this.form) {
            typeof this.form[k] == 'string' || typeof this.form[k] == 'number'
              ? (this.form[k] = v[k] || v[k] === 0 ? v[k] : '')
              : (this.form[k] = v[k] || v[k] === 0 ? [v[k]] : [])
          }
          this.form.organizationType = this.form.organizationType.toString()
        } else {
          for (let k in this.form) {
            typeof this.form[k] == 'string' || typeof this.form[k] == 'number'
              ? (this.form[k] = '')
              : (this.form[k] = [])
          }
        }
        this.$nextTick(() => {
          // console.log(this.form)
          this.$refs.form ? this.$refs.form.clearValidate() : null
        })
        if (v.method === 'add' && v.pid) {
          this.disabled = true
        } else {
          this.disabled = false
        }
      }
    },
    dialogFormVisible(v) {
      v
        ? null
        : this.$emit('input', !v && this.value.method == 'edit' ? null : v)
    },
  },
  methods: {
    judgeDisabled(item) {
      let value = this.value
      if (value && value.parentOrganizationType !== undefined) {
        let judgeParent =
          !isNaN(Number(item.dictCode)) &&
          !isNaN(Number(value.parentOrganizationType))
            ? Number(item.dictCode) < Number(value.parentOrganizationType)
            : !isNaN(Number(item.dictCode))
        let judgeChild =
          value.childOrganizationType === ''
            ? false
            : !isNaN(Number(item.dictCode)) &&
              !isNaN(Number(value.childOrganizationType))
            ? Number(item.dictCode) > Number(value.childOrganizationType)
            : isNaN(Number(value.childOrganizationType))
            ? false
            : isNaN(Number(item.dictCode))
        return judgeParent || judgeChild
      } else {
        return false
      }
    },
    returnTree(v) {
      this.$nextTick(() => {
        this.$refs.form.validateField('pid')
      })
    },
    getTree() {
      this.loading = true
      this.API.organization
        .totalList()
        .then((res) => {
          this.loading = false
          if (res.data) {
            let list = res.data || []
            this.menus = [
              { id: '0', organizationName: '快速开发平台', children: list },
            ]
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    submitForm() {
      if (this.ajaxIng) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // console.log(this.form)
          let param = {
            ...this.form,
          }
          param.pid ? null : (param.pid = '0')
          this.ajaxIng = true
          let title = this.title
          if (this.value.method === 'edit') {
            param.id = this.value.id
          }
          this.API.organization[
            `${
              this.value.method === 'edit' && this.value.id ? 'update' : 'add'
            }Organization`
          ](param)
            .then((res) => {
              this.$alertFn.success(`${title}成功 ！`)
              this.ajaxIng = false
              this.dialogFormVisible = false
              this.$emit('change')
            })
            .catch((err) => {
              this.ajaxIng = false
              // this.$alertFn.error(`${title}失败 ！`)
            })
        } else {
          // console.log('error submit!!')
          // this.$alertFn.error(`${title}失败，请修改 ！`)
          return false
        }
      })
    },
  },
}
</script>
<style scoped>
.helpTooltip {
  position: absolute;
  right: -24px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: #909399;
}
</style>